package org.lc.stk.web.controller.question;

import org.lc.stk.model.question.Question;
import org.lc.stk.service.question.QuestionService;
import org.lc.stk.web.dto.question.QuestionResponseDTO;
import org.lc.stk.web.response.ApiResponse;
import org.lc.stk.web.response.PageResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api/v1/questions")
@Tag(name = "试题管理", description = "试题的通用操作接口")
@SecurityRequirement(name = "bearerAuth")
public class QuestionController {

    private final QuestionService<QuestionResponseDTO> questionService;

    public QuestionController(QuestionService<QuestionResponseDTO> questionService) {
        this.questionService = questionService;
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取试题详情")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<QuestionResponseDTO>> getQuestion(
            @Parameter(description = "试题ID") @PathVariable Long id) {
        return questionService.getQuestionById(id)
                .map(question -> {
                    QuestionResponseDTO dto = new QuestionResponseDTO(question);
                    return ResponseEntity.ok(ApiResponse.success(dto));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除试题")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteQuestion(
            @Parameter(description = "试题ID") @PathVariable Long id) {
        questionService.deleteQuestion(id);
        return ResponseEntity.ok(ApiResponse.success());
    }

    @GetMapping
    @Operation(summary = "分页查询试题列表")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<PageResponse<QuestionResponseDTO>> listQuestions(Pageable pageable) {
        Page<QuestionResponseDTO> dtoPage = questionService.listQuestions(pageable);
        return ResponseEntity.ok(PageResponse.from(dtoPage));
    }
}